import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:visitor/result.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'Util.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'dart:async';
import 'dart:io';

class ShopPage extends StatefulWidget {
  ShopPage({Key key, this.title,this.para}) : super(key: key);
  final String title;
  final Map<String,dynamic> para;
  @override
  _ShopPage createState() => _ShopPage();
}

class _ShopPage extends State<ShopPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.para);
    loadData();
  }
  loadData() {
    SharedPreferences.getInstance().then((value){
      setState(() {
        String domain = value.getString("buildings").toMap()["subdomain"].toString();
        print(domain);
        var dic = widget.para;
        dic["api_key"] = "xQITe6bZFUrmeJbkcKgkUzajUI6FGLA";
        dic["lang"] = "en";
        print(dic);
        var dio = Dio();
        if (ShareHandle.instance.proxy.length > 0){
          (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
            client.findProxy = (uri) {
              return ShareHandle.instance.proxy;
            };
          };
        }
        dio.post("${domain}/api/block/listing",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          if (result.item2){
            setState(() {
              this.values1 = List<Map<String, dynamic>>.from(result.item1["container"] ?? []);
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error.toString());
        });
        dio.post("${domain}/api/floor/listing",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          if (result.item2){
            setState(() {
              this.values2 = List<Map<String, dynamic>>.from(result.item1["container"] ?? []);
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error.toString());
        });
        dio.post("${domain}/api/room/listing",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          if (result.item2){
            setState(() {
              this.values3 = List<Map<String, dynamic>>.from(result.item1["container"] ?? []);
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error.toString());
        });
      });
    });
  }
  Future scan() async {
    var result = await BarcodeScanner.scan();
    if (result.type == ResultType.Barcode){
      showDialog<Null>(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text(result.rawContent),
              //可滑动
              content: new SingleChildScrollView(
                child: new ListBody(
                  children: <Widget>[
                    new Text(''),
                  ],
                ),
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.of(context).pushNamed("result");
                  },
                ),
                new FlatButton(
                  child: new Text('取消'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          });
    }

    print(result.type); // The result type (barcode, cancelled, failed)
    print(result.rawContent); // The barcode content
    print(result.format); // The barcode format (as enum)
    print(result
        .formatNote); // If a unknown format was scanned this field contains a note
  }

  //"座數"
  List<Map<String, dynamic>> values1 = [];

  // "樓層"
  List<Map<String, dynamic>> values2 = [];

  //"單位"
  List<Map<String, dynamic>> values3 = [];

  List<Map<String,Map<String, dynamic>>> valuess = [];
  @override
  Widget build(BuildContext context) {
    List<Container> containers = [];

    List<DropdownMenuItem> items1 = [];
//    if (values1.length > 0 && values2.length > 0 && values3.length > 0){
//      valuess = [{
//        "a": values1[0],//"座數"
//        "b": values2[0],// "樓層"
//        "c": values3[0],//"單位"
//      }];
//    }
    for (var x in values1) {
      items1.add(DropdownMenuItem(
        child: Text(x["name"].toString()),
        value: x,
      ));
    }
    List<DropdownMenuItem> items2 = [];
    for (var x in values2) {
      items2.add(DropdownMenuItem(
        child: Text(x["name"].toString()),
        value: x,
      ));
    }
    List<DropdownMenuItem> items3 = [];
    for (var x in values3) {
      items3.add(DropdownMenuItem(
        child: Text(x["name"].toString()),
        value: x,
      ));
    }
    for (var v in valuess){
      containers.add(Container(//width: 335,
        //height: 368,
          margin: EdgeInsets.only(left: 35,right: 35,top: 10,bottom: 18),
          decoration: BoxDecoration(
            border: new Border.all(
              color: Colors.grey, //边框颜色
              width: 1, //边框宽度
            ), // 边色与边宽度
            color: Colors.white, // 底色
            boxShadow: [
              BoxShadow(
                blurRadius: 2, //阴影范围
                spreadRadius: 1, //阴影浓度
                color: Colors.grey, //阴影颜色
              ),
            ],
            borderRadius: BorderRadius.circular(19), // 圆角也可控件一边圆角大小
            //borderRadius: BorderRadius.only(
            //  topRight: Radius.circular(10),
            // bottomRight: Radius.circular(10)) //单独加某一边圆角
          ),
          child:Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Padding(
                    child: Text("座數",style: TextStyle(fontWeight: FontWeight.bold)),
                    padding: EdgeInsets.all(20),
                  ),
                  Expanded(
                    child: DropdownButton(
                      items: items1,
                      hint: Text("请选择"),
                      onChanged: (value) {
                        setState(() {
                          print(value);
                          v["a"] = value;
                        });
                      },
                      isExpanded: true,
                      value: v["a"],
                      elevation: 24, //设置阴影的高度
                      style: new TextStyle(
                        //设置文本框里面文字的样式
                        color: Color(0xff4a4a4a),
                        fontSize: 20,
                      ),
                      iconSize: 40.0,
                    ),
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Padding(
                    child: Text("樓層",style: TextStyle(fontWeight: FontWeight.bold)),
                    padding: EdgeInsets.all(20),
                  ),
                  Expanded(
                    child: DropdownButton(
                      items: items2,
                      hint: Text("请选择"),
                      onChanged: (value) {
                        setState(() {
                          v["b"] = value;
                        });
                      },
                      isExpanded: true,
                      value: v["b"],
                      elevation: 24, //设置阴影的高度
                      style: new TextStyle(
                        //设置文本框里面文字的样式
                        color: Color(0xff4a4a4a),
                        fontSize: 20,
                      ),
                      iconSize: 40.0,
                    ),
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Padding(
                    child: Text("單位",style: TextStyle(fontWeight: FontWeight.bold)),
                    padding: EdgeInsets.all(20),
                  ),
                  Expanded(
                    child: DropdownButton(
                      items: items3,
                      hint: Text("请选择"),
                      onChanged: (value) {
                        setState(() {
                          v["c"] = value;
                        });
                      },
                      isExpanded: true,
                      value: v["c"],
                      elevation: 24, //设置阴影的高度
                      style: new TextStyle(
                        //设置文本框里面文字的样式
                        color: Color(0xff4a4a4a),
                        fontSize: 20,
                      ),
                      iconSize: 40.0,
                    ),
                  )
                ],
              ),
            ],
          )));
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(padding: EdgeInsets.all(20),child: ListView(
        children: <Widget>[
          Text("請選擇到訪單位",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 21)),
          SizedBox(
            height: 20,
          ),
          Column(children: containers,),
          SizedBox(
            height: 20,
          ),
          MaterialButton(
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            height: 40,
            minWidth: 100,
            padding: EdgeInsets.all(0),
            color: Color(0xff0642ec),
            textColor: Colors.white,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20))),
            onPressed: () {
              setState(() {

                if (values1.length > 0 && values2.length > 0 && values3.length > 0){
                  valuess.add({
                    "a": values1[0],//"座數"
                    "b": values2[0],// "樓層"
                    "c": values3[0],//"單位"
                  });
                }
              });
            },
            child: Text("到訪更多單位"),
          ),
          SizedBox(
            height: 10,
          ),
          Row(mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Align(
                alignment: Alignment.centerLeft,
                child: MaterialButton(
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  height: 40,
                  minWidth: 100,
                  padding: EdgeInsets.all(0),
                  color: Color(0xff4a701e),
                  textColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(20))),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("上一步"),
                ),
              ),
              Align(
                alignment: Alignment.centerRight,
                child: MaterialButton(
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  height: 40,
                  minWidth: 100,
                  padding: EdgeInsets.all(0),
                  color: Color(0xff4a701e),
                  textColor: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(20))),
                  onPressed: () {
//                    scan();
//                    print(valuess);
                    var dic = widget.para;
                    dic["block_no"] = List.from(valuess.map((e) => e["a"]["code"].toString())).toJSONString();
                    dic["floor_no"] = List.from(valuess.map((e) => e["b"]["code"].toString())).toJSONString();
                    dic["room_no"] = List.from(valuess.map((e) => e["c"]["code"].toString())).toJSONString();
                    Navigator.push( context, MaterialPageRoute(builder: (context) => ResultPage(title: widget.title,para: dic)),);
                  },
                  child: Text("下一步"),
                ),
              ),
            ],
          ),
        ],
      ),),
    );
  }
}
